//
//  OauthViewController.swift
//  SinaWeiBo
//
//  Created by gxiangzi on 15/9/2.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit
import SVProgressHUD

class OauthViewController: UIViewController,UIWebViewDelegate {
    
    let webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoAdd")
        title = "新浪微博登陆"
        webView.delegate = self
        webView.loadRequest(NSURLRequest( URL: NetworkTools.sharedTools.OauthUrl))

    }
    override func loadView() {
        
        view = webView
    }
    
     // MARK: - 关闭 & 自动注入
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    @objc private func autoAdd() {
        
        let js = "document.getElementById('userId').value = 'gxiangzi@aliyun.com';" +
        "document.getElementById('passwd').value = '123456_gx';"
        
        webView.stringByEvaluatingJavaScriptFromString(js);
    }
    
     // MARK: - webView的代理方法
   func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    
        let url = request.URL!.absoluteString;
    
        if !url.hasPrefix(NetworkTools.sharedTools.backPage) {
            return true
        }
    
        if let query = request.URL!.query where query.hasPrefix("code=") {
            
            let code = query.substringFromIndex("code=".endIndex)
            
            // 回调网络方法，获得Token
//            UserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
//                printLog(error)
//                }, completed: { () -> Void in
//                    printLog("登录完成!")
//            })
            
            // 4. 调用网络方法，获取 token
            UserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
                printLog(error)
                }, completed: { () -> Void in
                    
                    SVProgressHUD.dismiss()
                    self.dismissViewControllerAnimated(true, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(GXSwitchRootViewControllerNotification, object: "nil", userInfo: nil)
                    })
                    
                    
            })
        
        } else {
            print("取消")
        }
        return false;
    }
    
   func webViewDidStartLoad(webView: UIWebView)
   {
        SVProgressHUD.show()
    }

    func webViewDidFinishLoad(webView: UIWebView)
    {
        SVProgressHUD.dismiss()
    }
}
